package tk.mybatis.springboot.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.socket.TextMessage;
import tk.mybatis.orderbyhelper.OrderByHelper;
import tk.mybatis.springboot.conf.SocketHandlerComponent;
import tk.mybatis.springboot.mapper.ChatLogMapper;
import tk.mybatis.springboot.mapper.FriendshipMapper;
import tk.mybatis.springboot.mapper.UserMapper;
import tk.mybatis.springboot.model.ChatLog;
import tk.mybatis.springboot.model.Message;
import tk.mybatis.springboot.model.Users;
import tk.mybatis.springboot.util.UserUtil;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * Created by denglei on 2017/4/17.
 */
@Controller
public class CoreController {

    @Autowired
    private UserMapper userMapper;

    @RequestMapping("")
    public String index(Model model,@ModelAttribute("key") String key){
        return "frame";
    }
    @RequestMapping("register")
    public String register(Model model){
        return "register";
    }
    @RequestMapping("/admin")
    public String admin(Model model,HttpSession session){
        model.addAttribute("me",session.getAttribute("me"));
        return "admin";
    }
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String login(){
        return "login";
    }
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(String username, String password, HttpSession session){
        Users users = userMapper.selectOne(new Users() {
            {
                setUsername(username);
                setPassword(password);
            }
        });
        if(null == users){
            throw new RuntimeException("用户名或者密码错误");
        }
        session.setAttribute("me",users);
            return "redirect:/";
    }

    @ExceptionHandler
    @ResponseBody
    public Object error(Exception e){
        e.printStackTrace();
        return new Message(e.getMessage(),false);
    }
    @Autowired
    private FriendshipMapper friendshipMapper;

    @RequestMapping(value = "/users",method = RequestMethod.GET)
    public String users(Model model){
        List<Users> userss = userMapper.selectAll();
        userss.forEach(users ->
            users.setIsFriend(friendshipMapper.isFriend(UserUtil.getLoginUser().getId(),users.getId()) > 0))
        ;
        model.addAttribute("list",userss);
        return "users";
    }
    @Autowired
    private SocketHandlerComponent socketHandlerComponent;

    @Autowired
    private ChatLogMapper chatLogMapper;
    @Autowired
    private ObjectMapper objectMapper;

    /**发送聊天记录
     * @param chatLog
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/msg",method = RequestMethod.POST)
    @ResponseBody
    public Object sendMessage(ChatLog chatLog) throws Exception {
        chatLog.setCreateTime(new Date());
        chatLog.setFrom(UserUtil.getLoginUser().getId());
        chatLog.setFromUser(UserUtil.getLoginUser());
        chatLog.setToUser(userMapper.selectByPrimaryKey(chatLog.getTo()));
        socketHandlerComponent.getSessionMap().get(chatLog.getTo()+"").sendMessage(
                new TextMessage(objectMapper.writeValueAsString(chatLog)));
        socketHandlerComponent.getSessionMap().get(chatLog.getFrom()+"").sendMessage(
                new TextMessage(objectMapper.writeValueAsString(chatLog)));
        chatLogMapper.insertSelective(
                chatLog
        );
        return new Message();
    }

    /**查看自己的聊天记录录
     * @param pageSize
     * @param pageNo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/msg",method = RequestMethod.GET)
    @ResponseBody
    public Object getMessage(@RequestParam(required = false,defaultValue = "10") Integer pageSize,
                             @RequestParam(required = false,defaultValue = "1")Integer pageNo) throws Exception {
        PageHelper.startPage(pageNo,pageSize);
        return chatLogMapper.myLog(UserUtil.getLoginUser().getId(),null);
    }
    /**查看指定用户的聊天记录录
     * @param pageSize
     * @param pageNo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/msg/{userId}",method = RequestMethod.GET)
    @ResponseBody
    public Object getMessage(@RequestParam(required = false,defaultValue = "10") Integer pageSize,
                             Integer userId,
                             @RequestParam(required = false,defaultValue = "1")Integer pageNo) throws Exception {
        PageHelper.startPage(pageNo,pageSize);
        return chatLogMapper.myLog(userId,null);
    }

    @RequestMapping(value = "/log/{userId}",method = RequestMethod.GET)
    public String getChatLogByUser(Model model,@PathVariable Integer userId){
         model.addAttribute("list",chatLogMapper.myLog(UserUtil.getLoginUser().getId(),userId));
         return "chat_log";
    }

    @RequestMapping(value = "/chat",method = RequestMethod.GET)
    public String chat(){
        return "chat";
    }
}
